package pers.qianyu.month_202012.date_20201208;

import org.junit.*;

import java.util.*;

/**
 * 27. 移除元素
 * https://leetcode-cn.com/problems/remove-element/
 *
 * @author mizzle rain
 * @date 2020-12-08 22:34
 */
public class RemoveElement {
    /**
     * 双指针
     */
    public int removeElement(int[] nums, int val) {
        if (nums == null) {
            return 0;
        }
        int slow = 0, fast = 0;
        while (fast < nums.length) {
            if (nums[fast] != val) {
                nums[slow] = nums[fast];
                slow++;
            }
            fast++;
        }
        return slow;
    }

    /**
     * 直接删
     */
    public int removeElement2(int[] nums, int val) {
        if (nums == null) {
            return 0;
        }
        int right = nums.length - 1;
        for (int i = 0; i <= right; i++) {
            if (nums[i] == val) {
                nums[i--] = nums[right--];
                System.out.println(Arrays.toString(nums));
            }
        }
        return right + 1;
    }

    @Test
    public void test2() {
        int[] arr = {0, 1, 2, 2, 3, 0, 4, 2};
        int result = new RemoveElement().removeElement2(arr, 2);
        System.out.println("result = " + result);
    }
}
